<template>
  <div>
    <div class="list">
      <el-tabs type="border-card" @tab-click="handleClick">
        <el-tab-pane label="当前咨询列表" style="height:500px;overflow-y:auto;" name="0">
          <h2 style="text-align:center;color:#858F99" v-show="chatTableList.length==0">当前没有咨询</h2>
          <el-card class="elcard" shadow="hover" @click.native="clickChatDetails(chat)" v-loading="loading" v-for="chat in chatTableList" :key="chat.chatTaId" :title="chat.member.memName">
            <el-tooltip class="item" effect="light" placement="right-start">
              <div slot="content"><el-button type="danger" size="mini" @click="delChatList(chat)" icon="el-icon-delete" circle title="从当前列表删除"></el-button></div>
              <div style="text-align:left;margin:0px;padding:0px">
                <el-badge :value="chat.noWatchCount==0?'':chat.noWatchCount" class="item">
                  <el-avatar shape="square" size="medium" :src="'http://192.168.43.183/files/'+chat.member.memImg"></el-avatar>
                </el-badge> &nbsp;&nbsp;
                <font size='3'>{{chat.member.memName}}</font>
                <span style="font-size:3px;color:#858F99;float:right">{{chat.lastTime}}</span>
              </div>
            </el-tooltip>
          </el-card>

        </el-tab-pane>
        <el-tab-pane label="历史咨询列表" style="height:500px;overflow-y:auto;" name="1">
          <h2 style="text-align:center;color:#858F99" v-show="chatTableList.length==0">无历史资讯</h2>
          <el-card class="elcard" shadow="hover" @click.native="clickChatDetails(chat)" v-loading="loading" v-for="chat in chatTableList" :key="chat.chatTaId" :title="chat.member.memName">
            <div style="text-align:left;margin:0px;padding:0px">
              <el-badge :value="chat.noWatchCount==0?'':chat.noWatchCount" class="item">
                <el-avatar shape="square" size="medium" :src="'http://192.168.43.183/files/'+chat.member.memImg"></el-avatar>
              </el-badge> &nbsp;&nbsp;
              <font size='3'>{{chat.member.memName}}</font>
              <span style="font-size:3px;color:#858F99;float:right">{{chat.lastTime}}</span>
            </div>
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 聊天框 -->
    <JwChat-index
      :config='config'
      :taleList='beforeObj.consultMsg'
      @enter='bindEnter'
      v-model='inputMsg'
      :toolConfig='tool'
      @clickTalk='talkEvent'
      class="jwchat_position"
    >
      <JwChat-talk class='rightSlot' :Talelist='talk' :config='quickConfig' @event='bindTalk' />
    </JwChat-index>

    <!-- 咨询人详细信息展示 -->
    <el-dialog title="咨询人信息" :visible.sync="dialogVisible" width="60%">
      <el-descriptions title="咨询人基本信息" border>
        <template slot="extra">
          <el-button type="success" @click="dialogVisible = false"> 关 闭 </el-button>
        </template>
        <el-descriptions-item label="姓名">{{watchMember.memName}}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{watchMember.memPhone}}</el-descriptions-item>
        <el-descriptions-item label="性别">{{watchMember.memGender}}</el-descriptions-item>
        <el-descriptions-item label="年龄">{{watchMember.memAge}}</el-descriptions-item>
        <el-descriptions-item label="籍贯">{{watchMember.memNativePlace}}</el-descriptions-item>
        <el-descriptions-item label="民族">{{watchMember.memNation}}</el-descriptions-item>
        <el-descriptions-item label="出生日期">{{watchMember.memBirthday}}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{watchMember.memEmail}}</el-descriptions-item>
        <el-descriptions-item label="婚姻状态">{{watchMember.memWedlock}}</el-descriptions-item>
        <el-descriptions-item label="职业">{{watchMember.memKarin}}</el-descriptions-item>
        <el-descriptions-item label="文化程度">{{watchMember.memDegree}}</el-descriptions-item>
        <el-descriptions-item label="个人说明" :span="3">{{watchMember.memDesc}}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions title="咨询人动态信息" :column="5" border style="margin: 30px 0">
        <el-descriptions-item label="身高(cm)">{{watchMemTrend.memTreHeight}}</el-descriptions-item>
        <el-descriptions-item label="体重(kg)">{{watchMemTrend.memTreWeight}}</el-descriptions-item>
        <el-descriptions-item label="舒张压(mmHg)">{{watchMemTrend.memTreDiastole}}</el-descriptions-item>
        <el-descriptions-item label="收缩压(mmHg)">{{watchMemTrend.memTreShrink}}</el-descriptions-item>
        <el-descriptions-item label="体温(℃)">{{watchMemTrend.memTreTemperature}}</el-descriptions-item>
        <el-descriptions-item label="呼吸频率(次/分钟)">{{watchMemTrend.memTreBreathe}}</el-descriptions-item>
        <el-descriptions-item label="腰围(cm)">{{watchMemTrend.memTreWaistline}}</el-descriptions-item>
        <el-descriptions-item label="臀围(cm)">{{watchMemTrend.memTreHip}}</el-descriptions-item>
        <el-descriptions-item label="BMI(体重指数)">{{watchMemTrend.memTreBmi}}</el-descriptions-item>
        <el-descriptions-item label="血氧饱和度">{{watchMemTrend.memTreOxygen}}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions title="咨询人病史信息" :column="1">
        <el-descriptions-item label="家族史">{{watchHistory.memCaseHisClan}}</el-descriptions-item>
        <el-descriptions-item label="手术史">{{watchHistory.memCaseHisOperation}}</el-descriptions-item>
        <el-descriptions-item label="过敏史">{{watchHistory.memCaseHisAllergy}}</el-descriptions-item>
        <el-descriptions-item label="病史">{{watchHistory.memCaseHisMedical}}</el-descriptions-item>
        <el-descriptions-item label="慢性病">{{watchHistory.memCaseHisChronic}}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

  <!-- 发送图片的file -->
  <input id="imgFile" type="file" @change="fileUploadImage()" accept=".gif,.jpg,.jpeg,.png" v-show="false">
  <!-- 发送文件的file -->
  <input id="fieldFile" type="file" @change="fileUploadField()" v-show="false">
  </div>
</template>

<script>
export default {
  data () {
    return {
      userInfo: {},
      inputMsg: '',
      tool: {
        show: ['video', 'img', ['发送文件', '发送图片']],
        callback: this.toolEvent
      },
      quickConfig: {
        nav: ['快捷回复'],
        showAdd: true,
        maxlength: 200,
        showHeader: true,
        showDeleteBtn: true
      },
      talk: [
      ],
      // 顶栏的展示
      config: {
        img: '',
        name: '',
        dept: '',
        memId: '',
        callback: this.bindCover
      },
      shortcuts: [], // 快捷信息列表
      chatTableList: [], // 消息列表数组
      loading: true, // 加载变量
      beforeObj: { consultMsg: [], chatTaId: null }, // 当前聊天对象
      isWho: 0,
      watchMember: {}, // 咨询人详细信息总表
      watchMemTrend: {}, // 咨询人动态信息从表
      watchHistory: {}, // 咨询人病史信息
      dialogVisible: false, // 打开对话框信息
      timeOut: null
    }
  },
  methods: {
    // 点击聊天框中的信息时触发
    talkEvent (play) {
      // alert('点击聊天信息或者头像信息时触发' + play)
      if (play.data.mine === false) {
        if (play.type === 'img') {
          this.$axios.post(`/api/DHMemberController/queryByMemIdMember?memId=${play.data.id}`).then(({data}) => {
            this.watchMember = data
          })
          this.$axios.post(`/api/DHMemberController/queryByMemIdTrends?memId=${play.data.id}`).then(({data}) => {
            this.watchMemTrend = data
          })
          this.$axios.post(`/api/DHMemberController/queryByMemIdCaseHistory?memId=${play.data.id}`).then(({data}) => {
            this.watchHistory = data
          })
          this.dialogVisible = true
        }
      } else if (play.data.mine === true) {
        if (play.type === 'img') {
          this.$message({
            showClose: true,
            message: '可以在主栏右上角的头像处查看个人信息哦～',
            type: 'warning'
          })
        }
      }
    },
    // 发送消息
    bindEnter () {
      const msg = this.inputMsg
      if (!msg) return
      // alert('点击发送触发' + msg)
      this.$axios.post(`/api/DHChatTableController/addConsultMsg?chatTaId=${this.beforeObj.chatTaId}&conMesType=0&conMesContent=${msg}&conMesState=${this.userInfo.hmId}&conMesAccount=${this.userInfo.hmUsername}`).then(result => {
        this.initChatTableList()
      })
    },
    // 打开发送文件和图片的方法
    toolEvent (type) {
      // alert('点击发送文件和图片触发')
      if (type === 'img') {
        document.getElementById('imgFile').click()
      } else if (type === 'video') {
        document.getElementById('fieldFile').click()
      }
    },
    // 查看聊天人信息
    bindCover (type) {
      // alert('点击顶栏个人信息时触发')
      this.$axios.post(`/api/DHMemberController/queryByMemIdMember?memId=${type.value.memId}`).then(({data}) => {
        this.watchMember = data
      })
      this.$axios.post(`/api/DHMemberController/queryByMemIdTrends?memId=${type.value.memId}`).then(({data}) => {
        this.watchMemTrend = data
      })
      this.$axios.post(`/api/DHMemberController/queryByMemIdCaseHistory?memId=${type.value.memId}`).then(({data}) => {
        this.watchHistory = data
      })
      this.dialogVisible = true
    },
    // 快捷回复
    bindTalk (play) {
      if (play.key === 'addTalk') {
        // alert('快捷回复确认添加' + play)
        this.$axios.post(`/api/ShortcutController/addShortcut?shoContent=${play.value}&hmId=${this.userInfo.hmId}`).then(result => {
          this.initShortcut()
          this.$message({
            type: 'success',
            message: '添加成功!'
          })
        })
      } else if (play.key === 'delIndex') {
        // alert('删除快捷')
        this.delShortcutById(play.value)
      } else if (play.key === 'select') {
        // alert('发送快捷')
        this.$axios.post(`/api/DHChatTableController/addConsultMsg?chatTaId=${this.beforeObj.chatTaId}&conMesType=0&conMesContent=${play.value}&conMesState=${this.userInfo.hmId}&conMesAccount=${this.userInfo.hmUsername}`).then(result => {
          this.initChatTableList()
        })
      }
    },
    // 加载个人信息的方法
    initUserInfo () {
      let user = JSON.parse(sessionStorage.getItem('user'))
      this.userInfo = user
      this.beforeObj = this.$store.state.chat
      this.beforeObj.consultMsg = []
      this.initShortcut()
      this.initChatTableList()
      // 如果不为空先清除
      if (this.timeOut != null) {
        clearInterval(this.timeOut)
      }
      // 开启计时器
      this.timeOut = setInterval(() => {
        this.initChatTableList()
      }, 3000)
    },
    // 加载快捷回复的方法
    initShortcut () {
      this.$axios.post(`/api/ShortcutController/queryByHmIdShortcut?hmId=${this.userInfo.hmId}`).then(({data}) => {
        this.shortcuts = data
        this.talk = []
        data.forEach(e => {
          this.talk.push(e.shoContent)
        })
      })
    },
    // 加载消息列表的方法
    initChatTableList () {
      this.$axios.post(`/api/DHChatTableController/initChatTableList?hmId=${this.userInfo.hmId}&chatTaState=${this.isWho}`).then(({data}) => {
        if (data != null && data !== '') {
          this.chatTableList = data
          this.loading = false
          if (this.beforeObj.chatTaId == null) {
            this.beforeObj = data[0]
            if (this.beforeObj === undefined) {
              this.beforeObj = { consultMsg: [], chatTaId: null }
            }
          }
          // 循环聊天列表，拿到当前聊天的对象
          this.chatTableList.forEach(e => {
            if (e.messagesList.length === 0) {
              e.lastTime = '无咨询记录'
            } else {
              let time = e.messagesList[e.messagesList.length - 1].conMesTime
              let date = new Date(time)
              let month = date.getMonth() + 1
              let day = date.getDate()
              day = day < 10 ? '0' + day : day
              let hours = date.getHours()
              let minutes = date.getMinutes()
              minutes = minutes < 10 ? '0' + minutes : minutes
              time = month + '/' + day + ' ' + hours + ':' + minutes
              if (date.getFullYear() !== new Date().getFullYear()) {
                time = e.messagesList[e.messagesList.length - 1].conMesTime
              }
              e.lastTime = time
            }

            if (this.beforeObj.chatTaId === e.chatTaId) {
              // 修改查看状态
              this.$axios.put(`/api/DHChatTableController/upConsultHmWatch?chatTaId=${this.beforeObj.chatTaId}`).then(result => {
                this.initChatTableList()
              })
              this.beforeObj = e
              this.beforeObj.consultMsg = []
              this.config.img = 'http://192.168.43.183/files/' + e.member.memImg
              this.config.name = e.member.memName
              this.config.dept = '个性签名：' + e.member.memDesc
              this.config.memId = e.member.memId
              // 循环聊天记录进行封装
              e.messagesList.forEach((con, i) => {
                let mine = false
                let name = ''
                let img = ''
                let text = ''
                let id = 0
                if (con.conMesState === e.hmId && con.conMesAccount === e.healthManager.hmUsername) {
                  mine = true
                  name = this.userInfo.hmName
                  img = 'http://192.168.43.183/files/' + this.userInfo.hmImg
                  id = this.userInfo.hmId
                } else {
                  mine = false
                  name = e.member.memName
                  img = 'http://192.168.43.183/files/' + e.member.memImg
                  id = e.member.memId
                }
                if (con.conMesType === 0) {
                  text = con.conMesContent
                } else if (con.conMesType === 1) {
                  text = '<img data-src="http://192.168.43.183/files/' + con.conMesContent + '"/>'
                } else if (con.conMesType === 2) {
                  if (mine === true) {
                    text = '<a style="" href="http://192.168.43.183/files/' + con.conMesContent + '" target="_blank">发送文件，点击查看</a>'
                  } else {
                    text = '<a style="color:red;" href="http://192.168.43.183/files/' + con.conMesContent + '" target="_blank">收到文件，点击查看</a>'
                  }
                } else {
                  text = con.conMesContent
                }
                let consult = {
                  'date': con.conMesTime,
                  'text': { 'text': text },
                  'mine': mine,
                  'name': name,
                  'img': img,
                  'id': id
                }
                this.beforeObj.consultMsg.push(consult)
              })
            }
          })
        } else {
          this.beforeObj = { consultMsg: [], chatTaId: null }
        }
      })
    },
    // 删除快捷回复
    delShortcutById (index) {
      this.$axios.delete(`/api/ShortcutController/${this.shortcuts[index].shoId}`).then(({data}) => {
        this.initShortcut()
      })
    },
    // 点击切换列表时触发
    handleClick (tab, event) {
      this.isWho = parseInt(tab.name)
      this.initChatTableList()
    },
    // 点击咨询人查看聊天详情
    clickChatDetails (chat) {
      this.beforeObj = chat
    },
    // 选择图片改变事件，进行发送
    fileUploadImage () {
      var files = document.getElementById('imgFile').files
      var params = new FormData()
      params.append('imgFile', files[0])
      this.$axios({
        url: `/api/DHChatTableController/fileUploadImage?chatTaId=${this.beforeObj.chatTaId}&conMesType=1&conMesState=${this.userInfo.hmId}&conMesAccount=${this.userInfo.hmUsername}`,
        method: 'post',
        data: params,
        headers: { 'Content-Type': 'multipart/form-data' }
      }).then(result => {
        if (result.data) {
          this.initChatTableList()
          this.$message({
            message: '图片发送成功',
            type: 'success'
          })
        } else {
          this.$message.error('发送失败，出现未知错误，请稍后再试')
        }
      })
    },
    // 选择文件的改变事件，进行发送
    fileUploadField () {
      var files = document.getElementById('fieldFile').files
      var params = new FormData()
      params.append('fieldFile', files[0])
      this.$axios({
        url: `/api/DHChatTableController/fileUploadField?chatTaId=${this.beforeObj.chatTaId}&conMesType=2&conMesState=${this.userInfo.hmId}&conMesAccount=${this.userInfo.hmUsername}`,
        method: 'post',
        data: params,
        headers: { 'Content-Type': 'multipart/form-data' }
      }).then(result => {
        if (result.data) {
          this.initChatTableList()
          this.$message({
            message: '文件发送成功',
            type: 'success'
          })
        } else {
          this.$message.error('文件发送失败，出现未知错误，请稍后再试')
        }
      })
    },
    // 从列表删除
    delChatList (chat) {
      this.$confirm('确定要将该列表移入历史列表中吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.put(`/api/DHChatTableController/delChatList?chatTaId=${chat.chatTaId}`).then(result => {
          this.$message({
            type: 'success',
            message: '移除成功!'
          })
          this.initChatTableList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消移除'
        })
      })
    }
  },
  created () {
    this.initUserInfo()
  }
}
</script>
<style>
.list{
  display: inline-block;
  width: 300px;
  position: absolute;
  left: 235px;
  top: 70px;
}
.jwchat_position{
  display: inline-block;
  position: relative;
  left: 159px;
}

.elcard{
  cursor: pointer;
}
.elcard:hover{
  background-color: #BBEEF5;
}
.ChatPage .header[data-v-177d6428] {
    background-color: rgba(43, 193, 231, 0.911);
}
.wrapper .web__main .web__main-item--mine .web__main-text[data-v-08a2a04c] {
  background-color:rgba(43, 193, 231, 0.911);
}
.wrapper .web__main .web__main-item--mine .web__main-text .web__main-arrow[data-v-08a2a04c]:after {
  border-left-color: #00d8dac9;
}
.el-button--primary {
  color: #FFF;
  background-color: rgba(43, 193, 231, 0.911);
  border-color: rgba(43, 193, 231, 0.911)
}
</style>
